use std::{path::Path, sync::RwLock};

use thunderdome::{Arena, Index};
use QcCore::resources::ResourceManager;
use QcTools::sync::OnceCell;

use crate::panel::ResFile;

static FILES: OnceCell<RwLock<Arena<ResFile>>> = OnceCell::new();

pub trait ResourceManagerExt {
    fn get_all_scene(&self) -> Vec<ResFile> {
        let mut result = vec![];
        if let Some(files) = FILES.get() {
            let files = files.try_read().unwrap();

            for (index, res) in files.iter() {
                if res.file_name.contains(".scene") {
                    result.push(res.clone());
                }
            }
        }

        result
    }

    fn get_file(&self, file_id: Index) -> Option<ResFile> {
        if let Some(files) = FILES.get() {
            let files = files.try_read().unwrap();

            if let Some(file) = files.get(file_id) {
                return Some(file.clone());
            }
        }

        None
    }

    fn get_file_by_name(&self, file_name: &str) -> Option<ResFile> {
        if let Some(files) = FILES.get() {
            let files = files.try_read().unwrap();

            for (index, res) in files.iter() {
                if res.file_name
                    == Path::new(file_name)
                        .file_name()
                        .unwrap()
                        .to_os_string()
                        .into_string()
                        .unwrap()
                {
                    return Some(res.clone());
                }
            }
        }

        None
    }

    fn add_file(&self, file: ResFile) -> Index {
        let mut files = FILES.get().unwrap().try_write().unwrap();
        files.insert(file)
    }

    fn init(&self) {
        FILES.set(RwLock::new(Arena::new())).unwrap();
    }

    fn clear(&self) {
        let mut files = FILES.get().unwrap().try_write().unwrap();
        files.clear();
    }
}

impl ResourceManagerExt for ResourceManager {}
